package com.frogs.ucenter.service.impl;

import java.util.Arrays;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import org.apache.commons.lang.ArrayUtils;
import org.jsoup.Connection.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.web.api.entity.ApiUrl;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.service.AbsService;
import com.frogs.ucenter.service.NewsService;

@Service("newsService")
public class NewsServiceImpl extends AbsService implements NewsService {
	
	private static Logger log = LoggerFactory.getLogger(NewsServiceImpl.class);
	
	private static ResourceBundle newsListBundle;
	public NewsServiceImpl() {
		newsListBundle = PropertyResourceBundle.getBundle("newsCategory");
	}

	/**
	 * 获取新闻资讯列表
	 */
	@Override
	public JSONObject getNewsList(String tag) {
		
		return null;
	}

	@Override
	public JSONObject getNewsList() throws Exception {
		String typeList = newsListBundle.getString("typeList");
		Integer pageSize = null == newsListBundle.getString("showSize") ? 10 :
						Integer.parseInt(newsListBundle.getString("showSize"));
		Integer pageNo = 1;
		
		ApiUrl apiUrl = this.buildMallApiBaseUrl("MALL_NEWS_LIST");
		String[] otherParams = {ApiUrlParamEnum.pageNo.getParamName(),pageNo.toString(),
								ApiUrlParamEnum.pageSize.getParamName(),pageSize.toString(),
								ApiUrlParamEnum.ids.getParamName(),typeList
								};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[listIndexNews] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("获取新闻资讯接口异常！");
		}
		return result;
	}
	
}
